# *-* coding:utf8 *-*
import redis
from flask import Flask, make_response, g, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from config import config
from flask_wtf.csrf import generate_csrf

from info.utils.common import user_login_data

db = SQLAlchemy()
redis_store = None
# csrf_token = generate_csrf()

def create_app(config_name):
    """通过传入不同的配置名字，初始化其对应配置的应用实例"""
    setup_log(config_name)
    app = Flask(__name__)

    # 从对象导入配置
    app.config.from_object(config[config_name])

    # 添加自定义过滤器
    from info .utils.common import to_index_class

    app.add_template_filter(to_index_class,'index_class')

    db.init_app(app)
    global redis_store
    # 配置ｒｅｄｉｓ
    redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT, decode_responses=True)
    # 开启ｃｓｒｆ保护
    CSRFProtect(app)
    Session(app)

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过 cookie 将值传给前端
        response.set_cookie('csrf_token',csrf_token)
        return response
    # 注册蓝图
    from info.modules.index import index_blu
    from info.modules.passport import pass_port_blu
    app.register_blueprint(index_blu)
    app.register_blueprint(pass_port_blu)

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    @app.errorhandler(404)
    @user_login_data
    def page_not_found(_):
        user = g.user
        data = {
            'user_info':user.to_dict()
        }
        return render_template('news/404.html',data=data)

    return app

def setup_log(config_name):
    '''配置日记'''
    # 设置日记等级
    import logging
    logging.basicConfig(level=config[config_name].LOG_LEVEL)
    from logging.handlers import RotatingFileHandler
    # 指定路径　文件大小　日记个数
    file__log_handler = RotatingFileHandler('logs/log',maxBytes=1024*1024*100,backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s  %(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file__log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file__log_handler)